﻿using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using BaseData.ReadAPI.Applications.Commands.User;
using BaseData.ReadAPI.DTO;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.ReadAPI.Applications.CommandHandlers.User
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserRoleDto>>
    {
        private readonly IBaseRepository<UserRoles> userolrRep;
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<Roles> roleRep;

        public LoginCommandHandler(IBaseRepository<UserRoles> userolrRep,IBaseRepository<Users> userRep,IBaseRepository<Roles> roleRep)
        {
            this.userolrRep = userolrRep;
            this.userRep = userRep;
            this.roleRep = roleRep;
        }
        public async Task<APIResult<UserRoleDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await userRep.GetAll().FirstOrDefaultAsync(x=>x.Account==request.accountname);
                if (res==null)
                {
                    return new APIResult<UserRoleDto>()
                    {
                        Code = CodeEnum.Failed,
                        Message = "账号不存在",
                        Data = null,
                    };
                }
                var user = userRep.GetAll().ToList();
                var urole = userolrRep.GetAll().ToList();
                var role = roleRep.GetAll().ToList();
                var result = request.pwd.GetMD5();
                var linq = from u in user
                           join ur in urole
                           on u.UsersId equals ur.UserId
                           join r in role
                           on ur.RoleId equals r.RoleId
                           where u.Account==request.accountname && u.Password == result
                           select new UserRoleDto
                           {
                               Account = u.Account,
                               Password = u.Password,
                               RoleId = r.RoleId,
                               RoleName = r.RoleName,
                               UserId = u.UsersId,
                               UserName = u.UserName,
                           };
                return new APIResult<UserRoleDto>()
                {
                    Code = CodeEnum.Success,
                    Message = "",
                    Data = linq.FirstOrDefault()
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
